package com.adcc.ags.gms.gw.controller;

import com.adcc.ags.gms.core.util.Constant;
import com.adcc.ags.gms.core.util.LogFactory;
import com.adcc.ags.gms.core.vo.ResultState;
import com.adcc.ags.gms.core.vo.ResultVO;
import com.adcc.ags.gms.gw.service.GMSLogService;
import com.adcc.ags.gms.gw.service.SysConfigurationService;
import com.adcc.ags.gms.gw.service.SysMonitorService;
import com.adcc.ags.gms.gw.service.UserMonitorService;
import com.adcc.ags.gms.gw.vo.*;
import com.adcc.utility.log.Log;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangpeng on 2016/9/19.
 */
@Controller
@RequestMapping(value = "/userMonitor", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserMonitorController {

    @Autowired
    private UserMonitorService userMonitorService;

    @Autowired
    private SysMonitorService sysMonitorService;

    @Autowired
    private GMSLogService logService;

    @Autowired
    private SysConfigurationService configurationService;
    @Autowired
    private LogFactory log;


    @RequestMapping(value = "/getAllMonitor", method = RequestMethod.GET)
    public @ResponseBody ResultVO getAllMonitor() {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<List<UserMonitorVO>> list = userMonitorService.findAllUserMonitor();
            if (list.isPresent() && list.get().size() > 0) {
                resultVO.getData().put("list", list.get());
            } else {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason("数据库暂无数据或查询失败！");
            }
            return resultVO;
        } catch (Exception e) {
            log.error(UserMonitorController.class,"findAllUserMonitor  fail", e);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason("服务器访问失败");
            return resultVO;
        }
    }

    @RequestMapping(value = "/getAllService", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> getAllService() {
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(5);
        try {
            AMQSMonitorVO amqsMonitorVO = sysMonitorService.getAmqsMonitor().isPresent() ? sysMonitorService.getAmqsMonitor().get() : null;
            MQInfoMonitorVO mqInfoMonitorVO = sysMonitorService.getMqMonitor().isPresent() ? sysMonitorService.getMqMonitor().get() : null;
            GWMonitorVO gwMonitorVO = sysMonitorService.getGWMonitor().isPresent() ? sysMonitorService.getGWMonitor().get() : null;
            result.put("AMQS", amqsMonitorVO);
            result.put("MQInfo", mqInfoMonitorVO);
            result.put("GW", gwMonitorVO);
        } catch (Exception e) {
            log.error(UserMonitorController.class,"getAllService() error", e);
        }
        return result;
    }

    @RequestMapping(value = "/getMonitorLogs", method = RequestMethod.GET)
    public @ResponseBody ResultVO getMonitorLogs(String logCount) {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<List<GWLogVO>> list = logService.findMonitorLogs(Integer.parseInt(logCount));
            if (list.isPresent() && list.get().size() > 0) {
                resultVO.getData().put("list", list.get());
            } else {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason("数据库暂无数据或查询失败！");
            }
            return resultVO;
        } catch (Exception e) {
            log.error(UserMonitorController.class,"getMonitorLogs  fail", e);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason("服务器访问失败");
            return resultVO;
        }
    }

    /**
     * 四舍五入取小数点后4位
     *
     * @param d
     * @return
     */
    private double getPoint(double d) {
        double result = 0;
        BigDecimal bd = new BigDecimal(d);
        result = bd.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
        return result;
    }

    public byte[] read(InputStream inStream) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outputStream.write(buffer);
        }
        inStream.close();
        return outputStream.toByteArray();
    }

    /**
     * 根据cmd命令检测网络状态*
     *
     * @return
     */
    @RequestMapping(value = "/checkNet", method = RequestMethod.GET)
    @ResponseBody public Map<String, Object> checkNet(String cmd,String ip,String pingNum) {
        if(Strings.isNullOrEmpty(ip) || Strings.isNullOrEmpty(cmd)){
            return null;
        }
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        //同sigar地址一样
//      String url = configurationService.getValue(Constant.MQSYS_MONITOR_URL)+cmd;
        String url = "http://192.168.246.197:9090/agent/NetWorkCheck/"+cmd;
        Map<String, Object> sysMap = Maps.newHashMapWithExpectedSize(2);
        try {
            HttpPost httpPost = new HttpPost(url);
            //设置超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(25000)
                    .setConnectTimeout(25000)
                    .setConnectionRequestTimeout(40000).build();
            httpPost.setConfig(requestConfig);
            client = HttpClients.createDefault();
            //参数（CMD命令）
            List<BasicNameValuePair> list = Lists.newArrayListWithExpectedSize(2);
            list.add(new BasicNameValuePair("ip", ip));
            //linux ping操作 需要加次数 -c pingNum
            if(url.contains("ping")){
                list.add(new BasicNameValuePair("count", pingNum));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            client.execute(httpPost);
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                String objectString = EntityUtils.toString(response.getEntity());
                if (objectString == null) {
                    sysMap.put("healthy", false);
                } else {
                    sysMap.put("healthy", true);
                    sysMap.put("message", objectString);
                }
                return sysMap;
            } else {
                return null;
            }
        } catch (Exception ex) {
            log.error(UserMonitorController.class, "checkNet() error", ex);
            return null;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    log.error(UserMonitorController.class, "close responseIO error", ex);
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException ex) {
                    log.error(UserMonitorController.class, "close clientIO error", ex);
                }
            }
        }
    }
}
